package com.igoal.web;

import java.io.File;
import java.util.Calendar;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.tuckey.web.filters.urlrewrite.utils.StringUtils;

import com.igoal.dto.UserDTO;
import com.igoal.service.GoalManager;
import com.igoal.service.MessageManager;
import com.igoal.service.UserManagerExt;
import com.igoal.utils.ImageUtils;
import com.igoal.web.model.AvatarModel;
import com.igoal.web.model.BaseModel;

@Controller
@RequestMapping("/editAvatar.html")
public class EditAvatarController extends BaseFormController {
	final int AVATAR_WIDTH = 74;
	
	@Override
	public String getViewPrefix() {
		return BaseControllerDelegate.DEFAULT_VIEW_PREFIX;
	}
	
	@Autowired
	public void setUserManagerExt(UserManagerExt userManagerExt) {
		this.userManagerExt = userManagerExt;
	}
	@Autowired
	public void setGoalManager(GoalManager goalManager) {
		this.goalManager = goalManager;
	}
	@Autowired
	public void setMessageManager(MessageManager messageManager){
		this.messageManager = messageManager;
	}
	
	public EditAvatarController(){
		setCommandName("avatarCommand");
		setCommandClass(AvatarModel.class);
		setFormView(getViewPrefix() + "editAvatar");
		setSuccessView("redirect:/dashboard.html");	
	}
	
	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		String avatarPath = request.getParameter("image");
		if(StringUtils.isBlank(avatarPath)){
			return new AvatarModel();
		}
		
		String serverPath = getServerPath();
		int[] size = new int[2];
		ImageUtils.getImageSize(serverPath + avatarPath, size);
		
		AvatarModel model = new AvatarModel();
		model.setImagePath(avatarPath);
		model.setWidth(size[0]);
		model.setHeight(size[1]);
		return model;
	}
	
	public String getServerPath(){
		String serverPath = getServletContext().getRealPath("");
		int lastSplash = serverPath.lastIndexOf(File.separator);
//		serverPath = serverPath.replace(File.separator + "ROOT", "");
		serverPath = serverPath.substring(0, lastSplash);
		return serverPath;
	}
	
	public String getFileExtension(String filenameExtension){
		int dotPos = filenameExtension.lastIndexOf(".");
	    String extension = filenameExtension.substring(dotPos);
	    return extension;
	}
	
	@Override
	protected ModelAndView onSubmit(Object command) throws Exception {
		AvatarModel model = (AvatarModel) command;
		
		UserDTO user = getUserSession();
		
		//TODO: remove hardcode
		String serverPath = getServerPath();
		String tempFilePath = serverPath + model.getImagePath();
		String repository = File.separator + "files" + File.separator + user.getUsername() + File.separator; 
		
		String finalFileName = Calendar.getInstance().getTime().getTime() + getUserInSession().hashCode() + getFileExtension(model.getImagePath());
		String finalFilePath = serverPath + repository + finalFileName;
		String cropFileName = "tmp."+finalFileName;
		String cropFilePath = serverPath + repository +  cropFileName;
		
		ImageUtils.cropImage(tempFilePath, cropFilePath, model.getHeight(), model.getWidth(), model.getX(), model.getY());
		ImageUtils.scaleAvatarImage(cropFilePath, finalFilePath, AVATAR_WIDTH);
		
		String webFilePath = repository + finalFileName;
		webFilePath = webFilePath.replace(File.separator, "/");
		userManagerExt.saveUserAvatar(user, webFilePath);
		
		return new ModelAndView(getSuccessView());
	}
	
	@SuppressWarnings("rawtypes")
	@Override
	protected Map referenceData(HttpServletRequest request) throws Exception {
		ModelMap modelMap = new ModelMap();
		BaseModel model = new BaseModel();
//		UserDTO user = getUserSession();		
//		simpleModelInitialize(user, model);
		initTopPage(model, request);
		initRightPage(model, request);
		initLeftPage(model, request);
		
		applyModel(modelMap, model);
		
		return modelMap;
	}

	public void initTopPage(BaseModel model, HttpServletRequest request) {
		UserDTO user = getUserSession();
		initTopZone(user, model);
	}

	public void initRightPage(BaseModel model, HttpServletRequest request) {
		UserDTO user = getUserSession();
		initRightZone(user, model);
	}

	public void initLeftPage(BaseModel model, HttpServletRequest request) {}
	
}
